package com.ruoyi.ruoyiqywechat.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.constant.CacheConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.JwtUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.qy.exception.CrmebException;
import com.ruoyi.common.qy.utils.UrlExtractor;
import com.ruoyi.common.qy.vo.DouYinVideoVo;
import com.ruoyi.common.redis.utils.RedisUtil;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.ruoyiqywechat.service.DouyinService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.awt.SystemColor.text;

/**
 * 抖音处理
 */
@RestController
@RequestMapping("/douyin/api")
public class DouYinController {
    // 更精确的抖音链接匹配
//    private static final Pattern DOUYIN_SPECIFIC_PATTERN = Pattern.compile(
//            "(https?://v\\.douyin\\.com/[^\\s]+?)(?=\\s*(复制|打开|$))"
//    );
    // 更强大的抖音链接匹配模式
    private static final Pattern DOUYIN_PATTERN = Pattern.compile(
            "(https?://v\\.douyin\\.com/[A-Za-z0-9]+/?)"
    );
    // 匹配从 http 开始到"复制"或"打开"之前的内容
    private static final Pattern LINK_PATTERN = Pattern.compile(
            "(https?://[^\\s]+?)(?=\\s*(复制|打开|$))"
    );

    /**
     * 从抖音分享文本中提取链接（主要方法）
     * 格式：文本内容 https://v.douyin.com/xxx/ 复制此链接...
     */
    public static Optional<String> extractLink(String shareText) {
        if (shareText == null || shareText.trim().isEmpty()) {
            return Optional.empty();
        }

        // 先尝试精确匹配抖音链接
        Matcher matcher = DOUYIN_PATTERN.matcher(shareText);
        ;
        if (matcher.find()) {
            return Optional.of(matcher.group(1).trim());
        }

        // 如果精确匹配失败，使用通用匹配
        matcher = LINK_PATTERN.matcher(shareText);
        if (matcher.find()) {
            return Optional.of(matcher.group(1).trim());
        }

        return Optional.empty();
    }
    public static void main(String[] args) {
        String text = "8.28 DhO:/ 09/10 u@S.yG 这十秒的视频 治愈了我一周的不开心# 柴犬小番茄  https://v.douyin.com/BD9JvUh7njw/ 复制此链接，打开Dou音搜索，直接观看视频！";
//        String text = "6.97 复制打开抖音，看看【桃子是只猫的作品】# 毛孩子也是孩子 # 萌宠出道计划 # 吉林消防... https://v.douyin.com/Xgi4wyB5Wqc/ g@b.nd Ljp:/ 08/05";
        System.out.println("抖音复制链接["+text+"]");

        // 提取单个链接
        Optional<String> link = extractLink(text);
        if (link.isPresent()) {
            System.out.println("✅ 提取到链接: " + link.get());
//            String videoUrl = extractAudioFromVideo(link.get());
//            System.out.println("抖音下载地址："+videoUrl);
        } else {
            System.out.println("❌ 未提取到链接");
        }

    }
    @Autowired
    private RedisUtil redisUtil;

    /**
     * （抖音）根据抖音分享链接提取视频链接url
     * @param map
     * @return
     */
    @PostMapping("getDouYinVideo")
    public R<HashMap<String, String> > getDouYinVideo(HttpServletRequest request,@RequestBody HashMap<String,String> map){
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isBlank(token)) {
            throw new CrmebException("请先登录!");
        }
        String userId = JwtUtils.getUserId(token);
        String text = map.get("text");
        System.out.println("getDouYinVideo抖音复制链接["+text+"]");
        HashMap<String, String> stringStringHashMap = new HashMap<>();
        stringStringHashMap.put("videoId",null);
        stringStringHashMap.put("url",null);
        // 提取单个链接
        Optional<String> link = extractLink(text);
        if (link.isPresent()) {
            System.out.println("✅ 提取到链接: " + link.get());
            String videoId = UrlExtractor.douyinUrlExtractor(link.get());
            DouYinVideoVo douYinVideoVo = DouYinVideoVo.getInstance();
            douYinVideoVo.setVideoId(videoId);
            douYinVideoVo.setUrl("");
            douYinVideoVo.setExtracting(true);
            douYinVideoVo.setExtractProgress(10);
            douYinVideoVo.setExtractStep(0);
            redisUtil.lSet(CacheConstants.DOUYIN_CREATE +userId, videoId,System.currentTimeMillis());//存顺序有序
            redisUtil.hset(CacheConstants.DOUYIN_CREATE_HASH +userId,videoId, JSONObject.toJSONString(douYinVideoVo));//hash存视频的详情信息
            douyinService.extractAudioFromVideo(userId,link.get(),videoId);
            stringStringHashMap.put("videoId",videoId);
            stringStringHashMap.put("url",null);
            return R.ok(stringStringHashMap);
        }
        throw new RuntimeException("未提取到链接");
    }
    /**
     * （抖音）根据抖音videoId查询是否已经生成成功的视频地址
     * @param videoId 视频ID
     * @return {"videoId":"视频ID","url":"视频地址",flag:false/true是否完成进度}
     */
    @PostMapping("listDouYinVideoById")
    public R<HashMap<String, Object> > listDouYinVideoById(HttpServletRequest request,String videoId){
        HashMap<String, Object> stringStringHashMap = new HashMap<>();
        stringStringHashMap.put("videoId",videoId);
        Object url = douyinService.listDouYinVideoById(request,videoId);
       stringStringHashMap.put("url",url);
       stringStringHashMap.put("flag",false);
       if(ObjectUtil.isNotNull(url)){
           stringStringHashMap.put("flag",true);
       }
       return R.ok(stringStringHashMap);
    }




    /**
     * （抖音）查询当前登录用户的所有视频
     * @return
     */
    @PostMapping("listDouYinVideoByUserId")
    public R<List<DouYinVideoVo>> listDouYinVideoByUserId(HttpServletRequest request){
       return  R.ok(douyinService.listDouYinVideoByUserId(request));
    }

    @Autowired
    private DouyinService douyinService;

    /**
     * （抖音）判断是否需要观看广告(true需要，false不需要)
     * @param video 视频ID
     * @return
     */
    @RequestMapping("queryWatchVideoNum")
    public R<Boolean> queryWatchVideoNum(HttpServletRequest request,@RequestParam("videoId")String video){
        return R.ok(douyinService.queryWatchVideoNum(request,video));
    }
    /**
     * （抖音）看完广告后累加广告次数
     * @param videoId 视频ID
     * @return
     */
    @RequestMapping("addWatchVideoNum")
    public void addWatchVideoNum(HttpServletRequest request,@RequestParam("videoId")String videoId){
        douyinService.addWatchVideoNum(request,videoId);
    }
}
